package com.example.ossdemo.ossController;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.example.modeldemo.base.Result;
import com.example.ossdemo.conf.FileTypeEnum;
import com.example.ossdemo.conf.OssConfig;
import com.example.ossdemo.entity.OssParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("oss")
@RefreshScope
public class OssController {

    @Autowired
    private OssConfig ossConfig;

    @RequestMapping("testOss")
    public void testOss(){
        System.out.println(ossConfig.getBucketName());
        System.out.println("测试oss");
    }

    /**
     * 获取存储空间列表
     * @return
     */
    @GetMapping("getBuckets")
    public Result getBuckets(){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        // 列举存储空间。
        List<Bucket> buckets = ossClient.listBuckets();
        // 关闭OSSClient。
        ossClient.shutdown();
        return Result.ok(buckets);
    }


    @PostMapping("uploadFile")
    public void uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        // objectName上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
        String objectName = DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_FORMAT) + "/"+file.getOriginalFilename();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        // 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（objectName）。
        PutObjectResult putObjectResult = ossClient.putObject(ossConfig.getBucketName(), objectName, file.getInputStream());
        System.err.println(JSONUtil.toJsonStr(putObjectResult));
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    /**
     * 获取文件列表
     * @param ossParams
     * @return
     */
    @PostMapping("getFileList")
    public Result getFileList(@RequestBody OssParams ossParams){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        String path = ossParams.getFolderPath() + "/";
        // ossClient.listObjects返回ObjectListing实例，包含此次listObject请求的返回结果。
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
        listObjectsRequest.setBucketName(ossParams.getBucketName());
        if (ObjectUtil.isEmpty(ossParams.getFolderPath())) {
            listObjectsRequest.setDelimiter("/");
        } else {
            listObjectsRequest.setDelimiter("/");
            listObjectsRequest.setPrefix(path);
        }
        ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
        List<JSONObject> list = new ArrayList<>();
        objectListing.getCommonPrefixes().forEach(v->{
            JSONObject jsonObject = new JSONObject();
            String name = v;
            if (ObjectUtil.isNotEmpty(path)){
                name = name.replace(path,"");
            }
            jsonObject.putOpt("type", FileTypeEnum.FOLDER_TYPE.getType());
            jsonObject.putOpt("name",name.replace("/",""));
            jsonObject.putOpt("path",v);
            list.add(jsonObject);
        });
        String https = "https://";
        objectListing.getObjectSummaries().stream().filter(f->f.getSize()>0).forEach(v->{
            JSONObject jsonObject = new JSONObject();
            jsonObject.putOpt("url",https+ossParams.getBucketName()+"."+ossConfig.getEndpoint().replace(https,"")+"/"+v.getKey());
            jsonObject.putOpt("name",v.getKey().replace(path,""));
            switch (v.getKey().substring(v.getKey().indexOf("."))){
                case ".txt":
                    jsonObject.putOpt("type",FileTypeEnum.TEXT_TYPE.getType());
                    break;
                case ".jpg":
                case ".jpeg":
                case ".gif":
                case ".png":
                    jsonObject.putOpt("type",FileTypeEnum.PICTURE_TYPE.getType());
                    break;
                case ".mp3":
                    jsonObject.putOpt("type",FileTypeEnum.MUSIC_TYPE.getType());
                    break;
                case ".doc":
                case ".docx":
                    jsonObject.putOpt("type",FileTypeEnum.WORD_TYPE.getType());
                    break;
                case ".ppt":
                    jsonObject.putOpt("type",FileTypeEnum.PPT_TYPE.getType());
                    break;
                case ".pdf":
                    jsonObject.putOpt("type",FileTypeEnum.PDF_TYPE.getType());
                    break;
                case ".xls":
                case ".xlsx":
                    jsonObject.putOpt("type",FileTypeEnum.EXCEL_TYPE.getType());
                    break;
                default:
                    jsonObject.putOpt("type",FileTypeEnum.OTHER_TYPE.getType());
                    break;
            }
            list.add(jsonObject);
        });
        // 关闭OSSClient。
        ossClient.shutdown();
        return Result.ok(list);
    }

}
